<template>
  <div class="map">
    <div class="action">
      <button >操作</button>
    </div>
    <div id="map"></div>
  </div>
</template>
<script>
import { getCurrentInstance, onMounted, reactive, ref } from "vue";
import axios from "axios";
export default {
  setup(props) {
    let map = null;
    let point = null;
    let ws = null;
    const object = reactive({
      points: [], //坐标数据
    });
    const init = () => {
      map = new BMapGL.Map("map"); // 创建Map实例
      point = new BMapGL.Point(116.404, 39.915); // 创建点坐标
      map.centerAndZoom(point, 15);
      map.enableScrollWheelZoom(); // 启用滚轮放大缩小
    };
    //增加覆盖物。
    const addMarker = () => {
      map.clearOverlays();
      map.centerAndZoom(
        new BMapGL.Point(object.points[0][0], object.points[0][1]),
        15
      );
      object.points.forEach((item, index) => {
        console.log("渲染车辆信息");
        // 创建小车图标
        let myIcon = new BMapGL.Icon("/imgs/car.png", new BMapGL.Size(23, 23));

        let marker = new BMapGL.Marker(new BMapGL.Point(item[0], item[1]), {
          icon: myIcon,
          enableDragging: true,
        });
        // marker.setRotation(90);//设置方向
        // marker.setShadow(1,2,3);
        map.addOverlay(marker);

        // 创建信息窗口
        let opts = {
          width: 200,
          height: 100,
          title: item[2].name,
        };
        let infoWindow = new BMapGL.InfoWindow("地址：" + item[2].desc, opts);
        // 点标记添加点击事件
        marker.addEventListener("click", () => {
          map.openInfoWindow(infoWindow, new BMapGL.Point(item[0], item[1])); // 开启信息窗口
        });
      });
    };

    let { proxy } = getCurrentInstance();

    //websocket发送消息
    const initWebsocket = () => {
      proxy.$ws.send("连接成功信息提示_李东泽");

      proxy.$ws.ws.onmessage = (res) => {
        console.log("服务端开始给我发送消息了", JSON.parse(res.data));

        object.points = JSON.parse(res.data);

        addMarker();
      };
    };

    onMounted(async () => {
      await init();
      //获取接口的数据，完成坐标数据渲染。
      await axios.get("http://localhost:3000/map").then((res) => {
        console.log(res.data.data);
        object.points = res.data.data;
      });

      await addMarker();

      await initWebsocket();
    });

    return {
    //   sendMsg,
    };
  },
};
</script>
<style lang="scss" scoped>
$w1: 300px;
$sh: 100vh;
.map {
  width: 100vw;
  height: $sh;
  display: flex;
  .action {
    width: $w1;
    border: #ddd 1px solid;
  }
  #map {
    flex: 1;
    height: $sh;
  }
}
</style>